package chapter07;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test03_add {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pstm = null;
        try{
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //连接数据库
            String url = "jdbc:mysql://localhost:3306/" +
                    "studentmanagement?serverTimezone=GMT%2B8&useSSL=false";
            con = DriverManager.getConnection(url,"root","root");
            //执行sql
            String sql = "insert into student values(NULL,?,?,?)";
            //装载preparedstatement
            pstm = con.prepareStatement(sql);
            pstm.setString(1,"113");
            pstm.setString(2,"王五");
            pstm.setString(3,"大数据2班");
            //返回操作成功的行数
            int i = pstm.executeUpdate();
            //查看运行结果
            System.out.println("成功插入了"+i+"行");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                pstm = null;
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                con = null;
            }
        }
    }
}
